import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:get/get.dart';
import 'dart:async';

class PlayerCont extends GetxController {
  // InAppWebViewController
  late InAppWebViewController controller;
  InAppWebViewSettings settings = InAppWebViewSettings(
      useHybridComposition: true,
      useShouldOverrideUrlLoading: true,
      allowFileAccessFromFileURLs: true,
      allowFileAccess: true,
      allowsInlineMediaPlayback: true,
      javaScriptCanOpenWindowsAutomatically: true,
      loadWithOverviewMode: true,
      mediaPlaybackRequiresUserGesture: false,
      isInspectable: true,
      javaScriptEnabled: true,
      ignoresViewportScaleLimits: true,
      allowContentAccess: true,
      allowUniversalAccessFromFileURLs: true,
      accessibilityIgnoresInvertColors: true,
      mixedContentMode: MixedContentMode.MIXED_CONTENT_ALWAYS_ALLOW);

  // 音频播放器
  late AudioPlayer player = AudioPlayer();
  var playerState  = PlayerState.disposed.obs;
  var duration = Duration.zero.obs;
  var position = Duration.zero.obs;
  // 用于解决slider边拖拽，边seek，导致卡顿问题
  // var positionTemp = Duration.zero.obs;

  // 回调
  StreamSubscription? _durationSubscription;
  StreamSubscription? _positionSubscription;
  StreamSubscription? _playerCompleteSubscription;
  StreamSubscription? _playerStateChangeSubscription;

  bool get isPlaying => playerState.value == PlayerState.playing;
  String get positionText => position.value.toString().split('.').first ?? '';
  String get durationText => duration.value.toString().split('.').first ?? '';
  double get sliderValue => duration.value.inMilliseconds > 0.0 ? position.value.inMilliseconds / duration.value.inMilliseconds : 0.0;


  String selectedValue = '选项2';
  List<String> items = ['选项1', '选项2', '选项3'];

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();

    initAudioPlayer();
  }

  // 初始化播放器
  void initAudioPlayer() async {
    _durationSubscription = player.onDurationChanged.listen((d) {
      duration.value = d;
    });
    _positionSubscription = player.onPositionChanged.listen((p) {
      position.value = p;
    });
    _playerCompleteSubscription = player.onPlayerComplete.listen((e) {
      print('==onPlayerComplete=====');
    });
    _playerStateChangeSubscription = player.onPlayerStateChanged.listen((s) {
      playerState.value = s;
    });

    await player.play(UrlSource('https://crawler.s3.bitiful.net/skuId_49190/B3DFAAE3D6C4B6A09C33DC5901307461/6HbLedfTQm-90.aac?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=ezHBEFglRootQjnWEojDYnO0%2F20250616%2F%2Fs3%2Faws4_request&X-Amz-Date=20250616T183052Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&x-id=GetObject&X-Amz-Signature=f09f3134ceb0260ce40efd2464ab3abced154df49b37372b1b22b02b8fcb8b88'));
  }
  // 播放按钮事件
  void playBtnOnClick() {
    if (playerState.value == PlayerState.playing) {
      player.pause();
    } else {
      player.resume();
    }
  }
  // 处理 position 和 duration 的显示
  String reduceText(String text) {
    if (text.startsWith('0:0')) {
      return text.replaceFirst('0:0', '');
    }
    if (text.startsWith('0:')) {
      return text.replaceFirst('0:', '');
    }
    return text;
  }
  // 处理slider拖拽
  void sliderOnChange(v) {
    final p = v * duration.value.inMilliseconds;
    // if ((p - position.value.inMilliseconds).abs() < 50000) return;
    // print("========$p");
    player.seek(Duration(milliseconds: p.round()));
  }

  // 加载页面
  void loadPage() {
    controller.loadFile(assetFilePath: 'assets/dp/dp.html');
  }

  // 设置handle
  void setJavaScriptHandler(BuildContext context) {
    // controller.addJavaScriptHandler(handlerName: 'getBase64FromBlobData', callback: (args) {
    //   // 先修改名字，再进行保存
    //   // dialog.show(Get.overlayContext!);
    //
    //   // print('=====${args[1]}');
    //
    //   // BrnMiddleInputDialog
    //   DateTime currentTime = DateTime.now();
    //   downloadToDevice('TDprogram_${currentTime.year}-${currentTime.month}-${currentTime.day}_${currentTime.hour}_${currentTime.minute}_${currentTime.second}.sb3', args[0]);
    // });
  }

  @override
  void onClose() {
    player.dispose();
    super.onClose();
  }
}